import React, { Component } from 'react';
import { connect } from 'dva';
import { Spin, Upload, Modal } from 'antd';
import moment from 'moment';
import EditPage from '@/components/EditPage';
import DetailPage from '@/components/DetailPage';
import FileReader from '@/components/FileReader';
import {
  queryDictData,
  formItemFragement,
  queryDict,
  queryPerson,
  queryFileList,
  formatPrice
} from '@/utils/common';
import { allDictList } from '@/utils/constans';
import { checkSuffix } from '@/pages/Common/common';
import {
  selectBillDetailAndInfo,
  renderTableAdSelect,
  billStatusList,
  allDispatchType,
  allUrl,
  renderTableAdSearch,
  upkeepPayMethod,
  incidentalStatusList
} from './utils';

@connect(({ vehicle, loading, component }) => ({
  detailsInfo: vehicle.detailsInfo,
  dictObject: component.dictObject,
  loading: loading.effects[allDispatchType.detailsInfo],
}))
export default class BillDetail extends Component {
  state = {
    // detailId: '',
    previewVisible: false,
    previewImage: '',
    fileList: [],
  };
  componentWillMount() {
    // 查询字典项
    const allDict = [
      allDictList.saleCompany,
      allDictList.oilType,
      allDictList.inspectionType,
      allDictList.upkeepType,
      allDictList.insuranceType,
      allDictList.insuranceObject,
      allDictList.currencyType,
      allDictList.papersType,
      allDictList.otherFeeType
    ];
    queryDict({ props: this.props, allDict });
  }

  componentDidMount() {
    const { detailId, type, open } = this.props;
    if (!detailId) return;
    this.queryFileList(detailId);
    selectBillDetailAndInfo({
      type: allDispatchType.detailsInfo,
      payload: { id: detailId, type, open },
      props: this.props,
      callback: res => {
        if (type == 'DRIVERPAPER') {
          const data = [res];
          res && queryPerson({ data, props: this.props, url: allUrl.userList });
        }
      },
    });
  }
  queryFileList = id => {
    const { type } = this.props;
    let fileBizType = '';
    if (type == 'OIL') {
      fileBizType = 'OIL_MANA';
    } else if (type == 'UPKEEP') {
      fileBizType = 'UPKEEP_MANA';
    } else if (type == 'ETCCHANGE') {
      fileBizType = 'ETC_CHANGE_MANA';
    } else if (type == 'INSURANCE') {
      fileBizType = 'INSURANCE_MANA';
    } else if (type == 'ANNUALAUDIT') {
      fileBizType = 'YEARAUDIT_MANA';
    } else if (type == 'DRIVERPAPER') {
      fileBizType = 'PAPERS';
    } else if (type == 'MISCELLANEOUS') {
      fileBizType = 'MISCELLANEOUS';
    }
    queryFileList({
      props: this.props,
      params: { bizId: id, fileBizType },
      callback: data => {
        if (!data) return;
        this.setState({ fileList: data });
      },
    });
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };
  formatfileList = fileList => {
    let _fileList = [];
    if (Array.isArray(fileList) && fileList.length > 0) {
      _fileList = fileList.map(file => {
        return {
          uid: file.id,
          name: file.fileUrl
            ? file.fileUrl.substring(file.fileUrl.lastIndexOf('\\') + 1, file.fileUrl.length)
            : '',
          status: 'done',
          url: `/server/api/tms/tms-attachment/readFile?path=${
            file.fileUrl
            }&token=${localStorage.getItem('token')}`,
          id: file.id,
        };
      });
    }
    // console.log('_fileList', _fileList);
    return _fileList;
  };
  handlePreview = file => {
    const checkFile = checkSuffix(file.name);
    if (file.name && !checkFile) {
      window.open(file.url);
      return;
    }
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };
  handleCancel = e => {
    this.setState({
      previewVisible: false,
    });
  };

  render() {
    const { loading, detailsInfo, detailId, type } = this.props;
    const { fileList } = this.state;
    const detail = detailsInfo[detailId] || {};
    const editPageParams = {
      panelTitle: ['基础信息'],
    };
    let formItem = [];

    //加油管理
    if (type == 'OIL') {
      formItem = [
        [
          <DetailPage label="单据号码" value={detail.oilNo} />,
          <DetailPage label="车牌号" value={detail.cartPlateNo} />,
        ],
        [<DetailPage label="公司" value={detail.ownCompanyName} />],
        [
          <DetailPage label="加油时间" value={detail.oilTime} />,
          <DetailPage label="加油站名称" value={detail.oilSiteName} />,
        ],
        [
          <DetailPage
            label="加油方式"
            value={renderTableAdSelect({
              props: this.props,
              value: detail.oilType,
              key: allDictList.oilType,
            })}
          />,
          <DetailPage label="油卡号" value={detail.oilCardNo} />,
        ],
        [
          <DetailPage label="加油人" value={detail.oilPerson} />,
          <DetailPage label="当前里程（KM）" value={detail.mileage} />,
        ],
        [
          <DetailPage label="加油量 （升）" value={detail.oilAmount} />,
          <DetailPage
            label="币种"
            value={renderTableAdSelect({
              props: this.props,
              value: detail.currencyType,
              key: allDictList.currencyType,
            })}
          />,
        ],
        [
          <DetailPage
            label="单价"
            value={detail.price && detail.price !== 0 ? Number(detail.price).toFixed(2) : 0}
          />,
          <DetailPage
            label="总金额"
            value={
              detail.totalFee && detail.totalFee !== 0 ? Number(detail.totalFee).toFixed(2) : 0
            }
          />,
        ],

        [<DetailPage label="备注" value={detail.remarks} />],

        [
          <DetailPage
            label="票据"
            value={
              <FileReader
                value={fileList}
                showUploadList={{ showPreviewIcon: true, showRemoveIcon: false }}
                showUpload={false}
                urlType="tms"
              />
            }
          />,
        ],
      ];
    }
    //维修保养管理
    if (type == 'UPKEEP') {
      const payAble =
        detail && detail.totalFee && Number(detail.totalFee) !== 0
          ? Number(detail.totalFee).toFixed(2)
          : '';
      const payActual =
        detail && detail.totalFee2 && Number(detail.totalFee2) !== 0
          ? Number(detail.totalFee2).toFixed(2)
          : '';
      formItem = [
        [
          <DetailPage label="单据号码" value={detail.upkeepNo} />,
          <DetailPage label="车牌号" value={detail.cartPlateNo} />,
        ],
        [
          <DetailPage label="公司" value={detail.ownCompanyName} />,
          <DetailPage
            label="类型"
            value={renderTableAdSelect({
              props: this.props,
              value: detail.upkeepType,
              key: allDictList.upkeepType,
            })}
          />,
        ],
        [
          <DetailPage
            label="应付币种"
            value={renderTableAdSelect({
              props: this.props,
              value: detail.currencyType,
              key: allDictList.currencyType,
            })}
          />,
          <DetailPage label="应付金额" value={payAble} />,
        ],
        [
          <DetailPage
            label="实付币种"
            value={renderTableAdSelect({
              props: this.props,
              value: detail.realCurrencyType,
              key: allDictList.currencyType,
            })}
          />,
          <DetailPage label="实付金额" value={payActual} />,
        ],
        [
          <DetailPage
            label="支付方式"
            //  value={detail.payMethod}
            value={renderTableAdSelect({
              props: this.props,
              value: detail.payMethod,
              data: upkeepPayMethod,
            })}
          />,
          <DetailPage label="送保时间/维修时间" value={detail.upkeepTime} />,
        ],
        [
          <DetailPage label="保养厂/维修厂" value={detail.upkeepFactory} />,
          <DetailPage label="送保人/送修人" value={detail.upkeepPerson} />,
        ],
        [<DetailPage label="当前里程" value={detail.currentMileage} />],
        [<DetailPage label="备注" value={detail.remarks} />],
        [
          <DetailPage
            label="票据"
            value={
              <FileReader
                value={fileList}
                showUploadList={{ showPreviewIcon: true, showRemoveIcon: false }}
                showUpload={false}
                urlType="tms"
              />
            }
          />,
        ],
      ];
    }
    //ETC管理
    if (type == 'ETCCHANGE') {
      const isRecharge = detail.tradingType == 'RECHARGE' ? true : false;
      formItem = [
        [
          <DetailPage label="单据号码" value={detail.etcChangeNo} />,
          <DetailPage label="车牌号" value={detail.cartPlateNo} />,
        ],
        [
          <DetailPage label="公司" value={detail.ownCompanyName} />,
          <DetailPage label="ETC卡号" value={detail.etcNo} />,
        ],
        [
          <DetailPage
            label="应付币种"
            value={renderTableAdSelect({
              props: this.props,
              value: detail.currencyType,
              key: allDictList.currencyType,
            })}
          />,
          <DetailPage
            label="金额"
            value={
              detail.changeMoney && detail.changeMoney !== 0
                ? Number(detail.changeMoney).toFixed(2)
                : 0
            }
          />,
        ],
        [<DetailPage label="备注" value={detail.remarks} />],
      ];
      if (isRecharge) {
        formItem.splice(2, 0, [<DetailPage label="充值地点" value={detail.locationName} />]);
      } else {
        formItem.splice(
          2,
          0,
          [
            <DetailPage label="入口时间" value={detail.entranceTime} />,
            <DetailPage label="入口站" value={detail.entranceStation} />,
          ],
          [
            <DetailPage label="出口时间/交易时间" value={detail.payMethod} />,
            <DetailPage label="出口站/交易站" value={detail.upkeepTime} />,
          ],
          [<DetailPage label="交易省份" value={detail.locationName} />]
        );
      }
      formItem.push([
        <DetailPage
          label="票据"
          value={
            <FileReader
              value={fileList}
              showUploadList={{ showPreviewIcon: true, showRemoveIcon: false }}
              showUpload={false}
              urlType="tms"
            />
          }
        />,
      ]);
    }
    //保险管理
    if (type == 'INSURANCE') {
      formItem = [
        [
          <DetailPage label="单据号码" value={detail.insuranceNo} />,
          <DetailPage label="车牌号" value={detail.cartPlateNo} />,
        ],
        [
          <DetailPage label="公司" value={detail.ownCompanyName} />,
          <DetailPage label="投保时间" value={detail.insuranceTime} />,
        ],
        [
          <DetailPage label="投保人" value={detail.insurancePerson} />,
          <DetailPage
            label="保险类型"
            value={renderTableAdSelect({
              props: this.props,
              value: detail.insuranceTypeCode,
              key: allDictList.insuranceType,
            })}
          />,
        ],
        [
          <DetailPage label="保险公司" value={detail.company} />,
          <DetailPage
            label="保险对象"
            value={renderTableAdSelect({
              props: this.props,
              value: detail.insuranceObject,
              key: allDictList.insuranceObject,
            })}
          />,
        ],
        [
          <DetailPage label="代理购买保险人" value={detail.agentPurchaser} />,
          <DetailPage label="被保险人" value={detail.applicant} />,
        ],
        [
          <DetailPage label="保单号" value={detail.insuranceCode} />,
          <DetailPage label="有效期" value={detail.expiryTime} />,
        ],
        [
          <DetailPage
            label="保费金额"
            value={
              detail.insuranceMoney && detail.insuranceMoney !== 0
                ? Number(detail.insuranceMoney).toFixed(2)
                : 0
            }
          />,
          <DetailPage
            label="币种"
            value={renderTableAdSelect({
              props: this.props,
              value: detail.currencyType,
              key: allDictList.currencyType,
            })}
          />,
        ],
        [<DetailPage label="备注" value={detail.remarks} />],
        [
          <DetailPage
            label="票据"
            value={
              <FileReader
                value={fileList}
                showUploadList={{ showPreviewIcon: true, showRemoveIcon: false }}
                showUpload={false}
                urlType="tms"
              />
            }
          />,
        ],
      ];
    }
    //年审管理
    if (type == 'ANNUALAUDIT') {
      formItem = [
        [
          <DetailPage label="单据号码" value={detail.annualNo} />,
          <DetailPage label="车牌号" value={detail.cartPlateNo} />,
        ],
        [
          <DetailPage label="公司" value={detail.ownCompanyName} />,
          <DetailPage label="时间" value={detail.yearAuditTime} />,
        ],
        [
          <DetailPage
            label="类型"
            value={renderTableAdSelect({
              props: this.props,
              value: detail.annualAuditType,
              key: allDictList.inspectionType,
            })}
          />,
          <DetailPage label="年审人" value={detail.yearAuditName} />,
        ],
        [
          <DetailPage
            label="年审金额"
            value={detail.feeCost && detail.feeCost !== 0 ? Number(detail.feeCost).toFixed(2) : 0}
          />,
          <DetailPage
            label="币种"
            value={renderTableAdSelect({
              props: this.props,
              value: detail.currencyType,
              key: allDictList.currencyType,
            })}
          />,
        ],
        [
          <DetailPage label="有效期" value={`${detail.expiryStartTime}~${detail.expiryEndTime}`} />,
          <DetailPage label="下次年审时间" value={detail.nextAnnualTime} />,
        ],
        [<DetailPage label="备注" value={detail.remarks} />],
        [
          <DetailPage
            label="票据"
            value={
              <FileReader
                value={fileList}
                showUploadList={{ showPreviewIcon: true, showRemoveIcon: false }}
                showUpload={false}
                urlType="tms"
              />
            }
          />,
        ],
      ];
    }

    //司机证件
    if (type == 'DRIVERPAPER') {
      formItem = [
        [
          <DetailPage label="单号" value={detail.papersNo} />,
          <DetailPage label="证件编号" value={detail.papersNumber} />,
        ],
        [
          <DetailPage label="所属公司" value={detail.mdsCompanyName} />,
          <DetailPage label="司机" value={detail.driverName} />,
        ],
        [
          <DetailPage
            label="证件类型"
            value={renderTableAdSelect({
              props: this.props,
              value: detail.papersType,
              key: allDictList.papersType,
            })}
          />,
          <DetailPage
            label="有效期"
            value={
              detail.expiryStartTime ? `${detail.expiryStartTime}~${detail.expiryEndTime}` : ''
            }
          />,
        ],
        [<DetailPage label="备注" value={detail.remarks} />],
        [
          <DetailPage
            label="附件"
            value={
              <FileReader
                value={fileList || []}
                showUploadList={{ showPreviewIcon: true, showRemoveIcon: false }}
                showUpload={false}
                urlType="tms"
              />
            }
          />,
        ],
      ];
    }

    //杂费
    if (type == 'MISCELLANEOUS') {
      formItem = [
        [
          <DetailPage label="单号" value={detail.miscellaneousNo} />,
          <DetailPage
            label="状态"
            value={renderTableAdSelect({
              props: this.props,
              value: detail.status,
              data: incidentalStatusList,
            })}
          />,
        ],
        [
          <DetailPage
            label="费用类型"
            value={renderTableAdSelect({
              props: this.props,
              value: detail.type,
              key: allDictList.otherFeeType,
            })}
          />,
          <DetailPage label="所属公司" value={detail.ownCompanyName} />,
        ],
        [
          <DetailPage label="付款人" value={detail.driverName} />,
          <DetailPage label="付款日期" value={detail.happenTime} />,
        ],
        [
          <DetailPage label="金额" value={formatPrice(detail.fee)} />,
          <DetailPage
            label="币种"
            value={renderTableAdSelect({
              props: this.props,
              value: detail.currency,
              key: allDictList.currencyType,
            })}
          />,
        ],
        [<DetailPage label="备注" value={detail.remark} />],
        [
          <DetailPage
            label="附件"
            value={
              <FileReader
                urlType="tms"
                value={fileList || []}
                showUploadList={{ showPreviewIcon: true, showRemoveIcon: false }}
                showUpload={false}
              />
            }
          />,
        ],
      ];
    }

    return (
      <div>
        <EditPage {...editPageParams}>
          <Spin spinning={loading}>{formItemFragement(formItem)}</Spin>
        </EditPage>
        <Modal visible={this.state.previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
        </Modal>
      </div>
    );
  }
}
